"""
======================
Author: 柠檬班-小简
Time: 2022/10/24 21:35
Project: day4_framwork_V2
Company: 湖南零檬信息技术有限公司
======================
"""
import json
import requests
from loguru import logger


class MyRequests:

    def __init__(self):
        self.header = {"locale": "zh_CN"}

    def send_requests(self, method, url, data=None, token=None, params=None,files=None):
        if token:
            self._deal_token(token)
        data = self.__deal_data(data)
        params = self.__deal_params(params)
        files = self.__deal_files(files)
        logger.info(f"请求方法为：{method}")
        logger.info(f"请求url为：{url}")
        if method.lower() == "get":
            logger.info(f"请求参数为：{params}")
            resp = requests.request(method, url, params=params,headers=self.header)
        elif files is not None:
            logger.info("本次请求，需要上传文件")
            logger.info(f"请求files值为：{files}")
            resp = requests.request(method, url, files=files, headers=self.header)
        else:
            logger.info(f"请求数据为：{data}")
            resp = requests.request(method, url, json=data, headers=self.header)
        logger.info("http请求完成....")
        logger.info(f"响应状态码：{resp.status_code}")
        logger.info(f"响应数据为：{resp.text}")
        return resp

    def _deal_token(self, token=None):
        if token:
            logger.info("本次请求需要鉴权。")
            self.header["Authorization"] = "bearer" + token
        logger.info(f"请求头为：{self.header}")

    def __deal_data(self,data):
        if data and isinstance(data, str):
            return json.loads(data) # 不用刻意去处理copy的请求数据中的null, true, false
        else:
            return data

    def __deal_params(self,params):
        if params and isinstance(params, str):
            return eval(params)
        else:
            return params

    def __deal_files(self,files):
        if files and isinstance(files, str):
            return eval(files)
        else:
            return files
